<?php

date_default_timezone_set('PRC');
include 'db.php';

function logwrite($str){
    $t = date('Y-m-d H:i:s ');
    $dir = __DIR__.'/log';
    if(!is_dir($dir)){
        mkdir($dir);
    }
    $file = $dir.'/gps-'. date('Y-m-d_H') .'.log';
    $wstr = $t.$str."\r\n\r\n" ;
    file_put_contents($file, $wstr,FILE_APPEND);
}


function getFlag($db){
    $flagres = $db->select("select * from flag");
    $flag=[];
    foreach($flagres as $k=>$v){
        $flag[$v['flag']] = $v['val'];
    }
    return $flag;
}


function curlPost($url,$data,$timeout = 5){
    if($url == '' || $timeout <=0){
        return false;
    }
    //echo $url;
    $con = curl_init((string)$url);
    curl_setopt($con, CURLOPT_HEADER, false);
    curl_setopt($con, CURLOPT_POSTFIELDS, http_build_query($data));
    curl_setopt($con, CURLOPT_POST,true);
    curl_setopt($con, CURLOPT_RETURNTRANSFER,true);
    curl_setopt($con, CURLOPT_TIMEOUT,(int)$timeout);
    return curl_exec($con);
}


function curlGet($url){
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_HEADER, 0);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    $data = curl_exec($curl);
    curl_close($curl);
    return $data;
}

function conn_com($fd ,$com_name,$baud='9600',$data = 8,$stop = 1)
{
    if($fd) return $fd;
    if(stripos(php_uname(),'windows')>-1){
        try {
            @exec("mode $com_name: baud=$baud data=$data stop=$stop parity=n xon=on");
            $fd = dio_open("$com_name:",O_RDWR);
        } catch(Exception $e) {
            echo "$com_name conn field \r\n";
            return false;
        }
        return $fd;
    }else{
        try{
            $fd = @dio_open($com_name, O_RDWR | O_NOCTTY | O_NONBLOCK);
            if(!$fd) return false;
            //dio_fcntl($fd, F_SETFL, O_SYNC);
            dio_tcsetattr($fd, array(
                'baud' => 9600,
                'bits' => 8,
                'stop'  => 1,
                'parity' => 0
            ));
        } catch(Exception $e){
            echo "$com_name conn field \r\n";
            return false;
        }
    }

    echo "$com_name success\r\n";
    return $fd;
}

//初始化配置文件并获取
function initConf(){
    $conf = [
            'sid'=>0,
            'gpsserver'=>'paver.zjzd-tech.com',
            'rtkserver'=>'base.zjzd-tech.com',
            'GpsSerialPort'=>'COM9',
            'GpsBaudRate'=>9600,
            'TempSerialPort'=>'/dev/tty.usbserial-FTGCT09O',
            'TempBaudRate'=>9600,
            'ShakeSerialPort'=>'/dev/ttyS1',
            'ShakeBaudRate'=>9600,
            'LedSerialPort'=>'/dev/ttyS7',
            'LedBaudRate'=>9600
            ];

    $configFile = __DIR__.'/config.json';
    if(!is_file($configFile)){
        file_put_contents($configFile, json_encode($conf));
        exit('new conf created.');
    }

    $confArr = file_get_contents($configFile);
    $conf = json_decode($confArr,true);
    $conf['car_type']='';
    return $conf;
}

//同步设备及摊铺工艺信息
function syncInitData($conf,$db){
    getconf:
    echo $url ='http://' . $conf['gpsserver'] . '/index.php?s=/ddc/index/getcenter';
    $res = curlPost($url,['sid'=>$conf['sid']]);
    echo $res;
    file_put_contents('debug.html', $res);
    if($res){
        echo "\ngetcenter ok \n";
        $data = json_decode($res, true);

        if($data['status']!='200'){
            return 0;
        }
        $nowtime= date('Y-m-d H:i:s');

                //获取设备列表
        foreach($data['devices'] as $key=>$car) {
            $cardata['sid'] = $car['id'];
            $cardata['name'] = $car['car_name'];
            $cardata['type'] = 2;
            $cardata['width'] = 1000;
            // $cardata['lon'] = $car['lon'];
            // $cardata['lat'] = $car['lat'];
            // $cardata['offset_x'] = $car['before_offset'];
            $cardata['update_time'] = $car['update_time'];
            // $cardata['paver_layer_id'] = $car['paver_layer_id'];
            // $cardata['roller_layer_id'] = $car['roller_layer_id'];
            if ($car['pav_left_offset']) {
                $cardata['offset_y'] = $car['pav_left_offset'] - $car['pav_right_offset'];
            } else {
                $cardata['offset_y'] = 0;
            }
            if ($car['id'] == $conf['sid']) $cur_car = $cardata;
            $db->update('carlist', $cardata, "sid=".$car['id'],1);
        }


        $sql = "delete from layer where id>0";
        $db->query($sql);
        //获取工艺层级
        foreach($data['layer'] as $layer){

            $layerData['id'] = $layer['id'];
            $layerData['subject_id'] = $layer['subject_id'];
            $layerData['layer_name'] = $layer['layer_name'];
            $layerData['point_type'] = $layer['point_style'];
            $layerData['shape_type'] = $layer['point_shape'];
            $layerData['size'] = $layer['diameter'];  //锤大小
            $layerData['area_margin'] = $layer['area_margin']; //外间距
            $layerData['height'] = $layer['height'];  //拉高
            $layerData['sort'] = $layer['sort'];
            $layerData['add_time'] = $layer['update_time'];
            $layerData['status'] = 0;
            $layerData['update_time'] = $nowtime;
            $db->insert('layer',$layerData);
        }

        $sql = "delete from area where id>0";
        $db->query($sql);
        //获取工艺层级
        foreach($data['area'] as $v){
            $area['id'] = $v['id'];
            $area['subject_id'] = $v['subject_id'];
            $area['area_name'] = $v['area_name'];
            $area['sort'] = $v['sort'];
            $area['update_time'] = $nowtime;
            $db->insert('area',$area);
        }

        echo $sql = "update flag set val=".$conf['sid'].",update_time='$nowtime' where flag='sid'";
        $db->query($sql);
       
        // // 设置当前设备类型
        // if ($cur_car){
        //     $sql = "update flag set val=".$cur_car['type'].",update_time='$nowtime' where flag='devicetype'";
        //     $db->query($sql);
        //     $sql = "update flag set val=".$cur_car['sid'].",update_time='$nowtime' where flag='sid'";
        //     $db->query($sql);
        //     $conf['car_type'] = $cur_car['type'];
        //     if($cur_car['type']==2){
        //         $sql = "update flag set val=0,update_time='$nowtime' where flag='roller_layer_id'";
        //         $db->query($sql);
        //     }
        // }
        return $conf;

    }

    //  检查是否同步成功
	$sql = "select count(*) nums from carlist";
	$carlist = $db->select($sql);
	if($carlist[0]['nums']){
	    $confdb =  getFlag($db);
	    $conf = array_merge($confdb,$conf);
	    return $conf;

	}else{
	    sleep(1);
	    echo date('Y-m-d H:i:s')." sync init data...\r\n"; 
	    goto getconf;
	}


    return 0;
}

//--------- run -------------
sleep(2);


$redisc = new \Redis();
$redisc->connect('127.0.0.1',6379);
// $redisc->set('shake',0);

$conf = initConf();



if(!isset($NOT_INIT)){
	$syncFlag = 0;  //开机启动是否同步成功一次
	for($i =0;$i<6;$i++){
	    echo "sync config $i ...\r\n";
	        $syncFlag =syncInitData($conf, $db);
	    if($syncFlag){
            $conf = $syncFlag;
		    echo "sync config success\r\n";
		break;
	    }
	    sleep(5);
	}
}



sleep(1);

// 检查是否同步成功



